package info.niwota.search;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.KeyPair;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class SearchServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(SearchServlet.class
			.getName());
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			req.getRequestDispatcher("/search.jsp").forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		handle(req, resp);
	}

	public void handle(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String service = req.getParameter("service");
			String keyword = req.getParameter("keyword");
			String data = req.getParameter("data");
			int cook = parseInt(req.getParameter("cook"), 1); //default obfuscate
			
			log.info("service: " + service + " keyword: " + keyword + " data: " + data);
			
			final HttpSession sess = req.getSession(true);
			sess.setAttribute(Constants.LAST_SERVICE, service);
			sess.setAttribute(Constants.LAST_COOK, cook +"");
			
			final KeyPair kp = (KeyPair) sess.getAttribute("public.keypair");
			
			log.fine("keypair: " + kp.getPublic() + " : " + kp.getPrivate());
			
			
			String kw = isEmpty(data) ? null : CryptUtils.decrypt(kp, data);
			
			log.fine("decrypted: " + kw);
			
			SearchEngine[] engines = (SearchEngine[]) sess.getAttribute("my.engines");
			if (engines == null) {
				engines = SearchEngine.getEngines();
				sess.setAttribute("my.engines", engines);
			}
			int idx = parseInt(service, 0);
			idx = (idx < 0 || idx >= engines.length ? 0 : idx);
			SearchEngine se = engines[idx];
			
			final String query = se.uri + (kw == null ? "" : URLEncoder.encode(kw, "UTF-8"));
			
			log.fine("query: " + query);
			
			//
			String[] terms = (kw == null ? null : kw.split("\\s"));
			
			HttpClient.fetch(query, terms, cook, req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean isEmpty(String s) {
		return s == null || s.equals("");
	}
	
	private int parseInt(String s, int def) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return def;
	}	
}
